﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KbWorksBlogMigrationtool.Properties;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;

namespace KbWorksBlogMigrationtool
{
    public class Approveitems
    {
        /// <summary>   
        /// Publishes the list item.   
        /// /// </summary>   
        /// /// <param name="item">The item.</param>   
        /// /// <param name="list">The list.</param>   
        /// /// <param name="settings">The settings.</param>   
        /// <param name="source">The source.</param>   
        internal static void PublishListItem(SPList list)
        {


            //approve all items  

            foreach (SPListItem item in list.Items)
            {

                if (item.Level == SPFileLevel.Published)
                    continue;

                SPFile sourceFile = item.File;
                if (sourceFile != null)
                {
                    //Update files  
                    if (sourceFile.Item.ModerationInformation.Status == SPModerationStatusType.Pending)
                    {
                        CancelWorkflows(list, item);
                        sourceFile.Approve("Bulk Approval by ME");
                    }
                }
                else
                {
                    //Update simple list items  
                    if (item.ModerationInformation.Status == SPModerationStatusType.Pending)
                    {
                        CancelWorkflows(list, item);
                        item.ModerationInformation.Status = SPModerationStatusType.Approved;
                        item.ModerationInformation.Comment = "Bulk Approval ME";
                        item.Update();
                    }
                }
            }
        }


        private static void CancelWorkflows(SPList list, SPListItem item)
        {

            if (list.DefaultContentApprovalWorkflowId != Guid.Empty)
            {

                SPSecurity.RunWithElevatedPrivileges(delegate
                {

                    foreach (SPWorkflow workflow in item.Workflows)
                    {

                        if (workflow.ParentAssociation.Id == list.DefaultContentApprovalWorkflowId)

                            SPWorkflowManager.CancelWorkflow(workflow);

                    }

                });

            }

        }

    }

}

